# V交流：18223205366
# 三要素转债第2版  yjl + float(price) - ytm_rt_format
# 评分=溢价率+价格-到期收益率  最终结果逆序
# -*- coding:utf-8 -*-
import json
import time
from operator import itemgetter

import requests

from constant.Constant import DIR_NAME, HEADER_2
from util.FileUtils import save_csv


def get_dat():
    # 定义请求头
    headers = {
        "user-agent": "Mozilla / 5.0(X11; Linux x86_64) AppleWebKit / 537.36(KHTML, likeGecko) "
                      "Chrome / 77.0.3865.120Safari / 537.36"}

    newUrl = "https://www.jisilu.cn/data/cbnew/cb_list/?___jsl=LST___t=1584777951900"
    # 不看交换债, 仅看已上市
    params = {'btype': 'C', 'listed': 'Y'}
    response = requests.post(newUrl, data=params, headers=headers)
    # 最简单的爬虫请求.也可以加上headers字段，防止部分网址的反爬虫机制
    # response = requests.get(newUrl)
    # 当爬取的界面需要用户名密码登录时候，构建的请求需要包含auth字段
    data = response.content.decode("utf-8")
    dat = json.loads(data)
    print(dat)

    # 所有数据
    lst_data = []
    for row in dat['rows']:
        # 每一条数据
        lst_dat = []
        # 转债id
        id = row["id"]
        # 排名
        rank = 1
        dat_cell = row["cell"]
        # 是否赎回
        is_shui = dat_cell['force_redeem']
        if is_shui == None:
            # 转债名称
            name = dat_cell['bond_nm']
            # 现价
            price = dat_cell['price']
            # 溢价率
            yjl = dat_cell['premium_rt']
            # 评级
            rating_cd = dat_cell['rating_cd']
            # 剩余时间
            last_time = dat_cell['year_left']
            # 剩余规模
            last_scale = dat_cell['orig_iss_amt']
            # 到期税前收益
            ytm_rt = dat_cell['ytm_rt']
            # 双低
            # dblow = dat_cell['dblow']

            # 溢价率去掉%，取2位小数点
            yjl_num = round(float(yjl.strip("%")), 2)
            if yjl_num > 15:
                continue
            # 到期税前收益去掉%，取2位小数点
            ytm_rt_num = round(float(ytm_rt.strip("%")), 2)
            if ytm_rt_num <= 0:
                continue

            if yjl_num > 15:
                continue
            ytm_rt_num = round(float(ytm_rt.strip("%")), 2)
            if ytm_rt_num <= 0:
                continue
            score = round(yjl_num + float(price) - ytm_rt_num, 2)

            lst_dat.append(rank)
            lst_dat.append(score)
            lst_dat.append(id)
            lst_dat.append(name)
            lst_dat.append(rating_cd)
            lst_dat.append(last_time)
            lst_dat.append(last_scale)
            # lst_dat.append(dblow)
            lst_dat.append(price)
            lst_dat.append(yjl)
            lst_dat.append(ytm_rt)
            lst_data.append(lst_dat)
        else:
            continue

    lst_data = sorted(lst_data, key=itemgetter(1), reverse=False)

    for index in range(len(lst_data)):
        lst_data[index][0] = index + 1

    return lst_data


def wirte_csv(data):
    # 格式化成2016-03-20形式
    today = time.strftime("%Y-%m-%d", time.localtime())
    path = DIR_NAME + '/' + '可转债' + today + '-02.csv'
    save_csv(path, HEADER_2, data)


def get_three_elements2():
    data = get_dat()
    wirte_csv(data)


if __name__ == '__main__':
    data = get_dat()
    wirte_csv(data)
